n<template>
	<AdminLayout activeKey="analytics" :breadcrumbs="['首页','数据分析']" tabTitle="数据分析">
		<view class="analytics-page">
			<!-- 顶部工具栏 -->
			<view class="toolbar">
				<view class="toolbar-left">
					<view class="page-header">
						<text class="page-title">运营数据看板</text>
						<text class="page-subtitle">实时监控平台运营情况与风险指标</text>
					</view>
				</view>
				<view class="toolbar-right">
					<picker mode="date" fields="month" @change="onMonthChange" class="date-picker">
						<view class="picker-btn">
							<text class="iconfont icon-riqi"></text>
							<text class="picker-text">{{ month || '全部月份' }}</text>
						</view>
				</picker>
					<button class="toggle-data-btn" @click="toggleDataSource" :class="{ active: useRealData }">
						<text class="iconfont icon-qiehuan"></text>
						<text>{{ useRealData ? '真实数据' : '模拟数据' }}</text>
					</button>
					<button class="refresh-btn" @click="loadAllData">
						<text class="iconfont icon-shuaxin"></text>
						<text>刷新数据</text>
					</button>
				</view>
			</view>

			<!-- 核心指标卡片 -->
			<view class="overview-cards">
				<view class="metric-card" v-for="(metric, index) in overviewMetrics" :key="index">
					<view class="metric-icon" :style="{ background: metric.color }">
						<text class="iconfont" :class="metric.icon"></text>
					</view>
					<view class="metric-content">
						<view class="metric-value">{{ metric.value }}</view>
						<view class="metric-label">{{ metric.label }}</view>
						<view class="metric-trend" :class="{ positive: metric.trend > 0, negative: metric.trend < 0 }">
							<text class="trend-icon">{{ metric.trend > 0 ? '↗' : metric.trend < 0 ? '↘' : '→' }}</text>
							<text class="trend-text">{{ Math.abs(metric.trend) }}%</text>
						</view>
					</view>
				</view>
			</view>

			<!-- 数据分析区域 -->
			<view class="analytics-grid">
				<!-- 用户数据分析 -->
				<view class="chart-panel">
					<view class="panel-header">
						<view class="panel-title">
							<text class="iconfont icon-yonghu panel-icon"></text>
							<text>用户数据分析</text>
						</view>
						<view class="panel-tabs">
							<text class="tab-item" :class="{ active: userActiveTab === 'growth' }" @click="switchUserTab('growth')">用户增长</text>
							<text class="tab-item" :class="{ active: userActiveTab === 'active' }" @click="switchUserTab('active')">活跃度</text>
						</view>
					</view>
					<view class="chart-container">
						<QiunDataCharts 
							type="line" 
							:opts="userChartOpts"
							:chartData="userChartData"
							:loadingType="1"
							background="transparent"
							canvas2dH5="true"
							:canvas2dH5Width="600"
							:canvas2dH5Height="400"
						/>
					</view>
					<view class="chart-stats">
						<view class="stat-item">
							<text class="stat-label">总用户数</text>
							<text class="stat-value">{{ userStats.total }}</text>
						</view>
						<view class="stat-item">
							<text class="stat-label">本月新增</text>
							<text class="stat-value">{{ userStats.monthlyNew }}</text>
						</view>
						<view class="stat-item">
							<text class="stat-label">活跃用户</text>
							<text class="stat-value">{{ userStats.active }}</text>
						</view>
					</view>
				</view>

				<!-- 任务数据分析 -->
				<view class="chart-panel">
					<view class="panel-header">
						<view class="panel-title">
							<text class="iconfont icon-renwu panel-icon"></text>
							<text>任务数据分析</text>
						</view>
						<view class="panel-tabs">
							<text class="tab-item" :class="{ active: taskActiveTab === 'volume' }" @click="switchTaskTab('volume')">发布量</text>
							<text class="tab-item" :class="{ active: taskActiveTab === 'completion' }" @click="switchTaskTab('completion')">完成率</text>
							<text class="tab-item" :class="{ active: taskActiveTab === 'category' }" @click="switchTaskTab('category')">分类</text>
						</view>
					</view>
					<view class="chart-container">
						<QiunDataCharts 
							:type="taskChartType" 
							:opts="taskChartOpts"
							:chartData="taskChartData"
							:loadingType="1"
							background="transparent"
							canvas2dH5="true"
							:canvas2dH5Width="600"
							:canvas2dH5Height="400"
						/>
					</view>
					<view class="chart-stats">
						<view class="stat-item">
							<text class="stat-label">总任务数</text>
							<text class="stat-value">{{ taskStats.total }}</text>
						</view>
						<view class="stat-item">
							<text class="stat-label">已完成</text>
							<text class="stat-value">{{ taskStats.completed }}</text>
						</view>
						<view class="stat-item">
							<text class="stat-label">完成率</text>
							<text class="stat-value">{{ taskStats.completionRate }}%</text>
						</view>
					</view>
				</view>

				<!-- 交易数据分析 -->
				<view class="chart-panel">
					<view class="panel-header">
						<view class="panel-title">
							<text class="iconfont icon-jiaoyi panel-icon"></text>
							<text>交易数据分析</text>
						</view>
						<view class="panel-tabs">
							<text class="tab-item" :class="{ active: tradeActiveTab === 'amount' }" @click="switchTradeTab('amount')">交易额</text>
							<text class="tab-item" :class="{ active: tradeActiveTab === 'volume' }" @click="switchTradeTab('volume')">交易量</text>
							<text class="tab-item" :class="{ active: tradeActiveTab === 'habit' }" @click="switchTradeTab('habit')">消费习惯</text>
						</view>
					</view>
					<view class="chart-container">
						<QiunDataCharts 
							:type="tradeChartType" 
							:opts="tradeChartOpts"
							:chartData="tradeChartData"
							:loadingType="1"
							background="transparent"
							canvas2dH5="true"
							:canvas2dH5Width="600"
							:canvas2dH5Height="400"
						/>
					</view>
					<view class="chart-stats">
						<view class="stat-item">
							<text class="stat-label">总交易额</text>
							<text class="stat-value">¥{{ tradeStats.totalAmount }}</text>
						</view>
						<view class="stat-item">
							<text class="stat-label">交易笔数</text>
							<text class="stat-value">{{ tradeStats.totalCount }}</text>
						</view>
						<view class="stat-item">
							<text class="stat-label">平均客单</text>
							<text class="stat-value">¥{{ tradeStats.avgAmount }}</text>
						</view>
					</view>
				</view>

				<!-- 风险监控面板 -->
				<view class="risk-panel">
					<view class="panel-header">
						<view class="panel-title">
							<text class="iconfont icon-jinggao panel-icon risk-icon"></text>
							<text>风险数据监控</text>
						</view>
						<view class="risk-level" :class="riskLevel.class">
							<text class="risk-dot"></text>
							<text class="risk-text">{{ riskLevel.text }}</text>
						</view>
					</view>
					
					<view class="risk-metrics">
						<view class="risk-metric-card">
							<view class="risk-metric-header">
								<text class="risk-metric-title">高违约率任务类型</text>
								<text class="risk-metric-count">{{ riskData.highDefaultTasks.length }}</text>
							</view>
							<view class="risk-list">
								<view class="risk-item" v-for="item in riskData.highDefaultTasks" :key="item.type">
									<text class="risk-item-name">{{ item.type }}</text>
									<text class="risk-item-rate">{{ item.rate }}%</text>
								</view>
							</view>
						</view>

						<view class="risk-metric-card">
							<view class="risk-metric-header">
								<text class="risk-metric-title">频繁违规用户</text>
								<text class="risk-metric-count">{{ riskData.violationUsers.length }}</text>
							</view>
							<view class="risk-list">
								<view class="risk-item" v-for="user in riskData.violationUsers" :key="user.id">
									<text class="risk-item-name">{{ user.nickname }}</text>
									<text class="risk-item-count">{{ user.violationCount }}次</text>
								</view>
							</view>
			</view>

						<view class="risk-metric-card">
							<view class="risk-metric-header">
								<text class="risk-metric-title">异常交易监控</text>
								<text class="risk-metric-count">{{ riskData.abnormalTransactions.length }}</text>
							</view>
							<view class="risk-list">
								<view class="risk-item" v-for="transaction in riskData.abnormalTransactions" :key="transaction.id">
									<text class="risk-item-name">{{ transaction.description }}</text>
									<text class="risk-item-level" :class="transaction.level">{{ transaction.levelText }}</text>
								</view>
							</view>
						</view>
					</view>
				</view>
			</view>

		</view>
	</AdminLayout>
</template>

<script>
import AdminLayout from '@/components/AdminLayout.vue'
import QiunDataCharts from '@/uni_modules/qiun-data-charts/components/qiun-data-charts/qiun-data-charts.vue'

export default {
	components: { 
		AdminLayout,
		QiunDataCharts
	},
	data() {
		return {
			month: '',
			loading: false,
			useRealData: false, // 是否使用真实数据
			
			// 核心指标数据
			overviewMetrics: [
				{ label: '总用户数', value: '0', trend: 0, color: 'linear-gradient(135deg, #667eea 0%, #764ba2 100%)', icon: 'icon-yonghu' },
				{ label: '活跃任务', value: '0', trend: 0, color: 'linear-gradient(135deg, #f093fb 0%, #f5576c 100%)', icon: 'icon-renwu' },
				{ label: '交易金额', value: '¥0', trend: 0, color: 'linear-gradient(135deg, #4facfe 0%, #00f2fe 100%)', icon: 'icon-jiaoyi' },
				{ label: '风险指数', value: '低', trend: 0, color: 'linear-gradient(135deg, #43e97b 0%, #38f9d7 100%)', icon: 'icon-anquan' }
			],
			
			// 用户数据
			userActiveTab: 'growth',
			userStats: {
				total: 0,
				monthlyNew: 0,
				active: 0
			},
			userChartData: {},
			userChartOpts: {},
			
			// 任务数据
			taskActiveTab: 'volume',
			taskStats: {
				total: 0,
				completed: 0,
				completionRate: 0
			},
			taskChartData: {},
			taskChartOpts: {},
			
			// 交易数据
			tradeActiveTab: 'amount',
			tradeStats: {
				totalAmount: '0.00',
				totalCount: 0,
				avgAmount: '0.00'
			},
			tradeChartData: {},
			tradeChartOpts: {},
			
			// 风险数据
			riskLevel: {
				text: '低风险',
				class: 'low'
			},
			riskData: {
				highDefaultTasks: [],
				violationUsers: [],
				abnormalTransactions: []
			},
			
		// 真实数据存储
		realUserGrowthData: null,
		realTaskVolumeData: null,
		realTaskCompletionData: null,
		realTaskCategoryData: null,
		realTradeChartData: null,
		realTradeHabitData: null
		}
	},
	
	computed: {
		// 获取任务图表类型
		taskChartType() {
			if (this.taskActiveTab === 'completion') {
				return 'line'
			} else {
				return 'column'
			}
		},
		
		// 获取交易图表类型
		tradeChartType() {
			if (this.tradeActiveTab === 'amount') {
				return 'area'
			} else if (this.tradeActiveTab === 'volume') {
				return 'line'
			} else {
				return 'column'
			}
		}
	},
	
	onReady() {
		this.loadAllData()
	},
	
	
	methods: {
		onMonthChange(e) {
			this.month = e.detail.value
			this.loadAllData()
		},
		
		// 切换数据源
		toggleDataSource() {
			this.useRealData = !this.useRealData
			uni.showToast({
				title: `已切换到${this.useRealData ? '真实' : '模拟'}数据`,
				icon: 'success',
				duration: 1500
			})
			this.loadAllData()
		},
		
		// 切换用户图表tab
		switchUserTab(tab) {
			this.userActiveTab = tab
			this.setupUserChart()
		},
		
		// 切换任务图表tab
		switchTaskTab(tab) {
			this.taskActiveTab = tab
			this.setupTaskChart()
		},
		
		// 切换交易图表tab
		switchTradeTab(tab) {
			this.tradeActiveTab = tab
			this.setupTradeChart()
		},
		
		// 图表事件处理
		getUserChartIndex(e) {
			console.log('用户图表点击:', e);
		},
		
		getTaskChartIndex(e) {
			console.log('任务图表点击:', e);
		},
		
		getTradeChartIndex(e) {
			console.log('交易图表点击:', e);
		},
		
		
		async loadAllData() {
			this.loading = true
			try {
				await Promise.all([
					this.loadUserData(),
					this.loadTaskData(),
					this.loadTradeData(),
					this.loadRiskData()
				])
				this.updateOverviewMetrics()
				this.$nextTick(() => {
					this.setupAllCharts()
					console.log('图表配置已加载:', {
						userChartOpts: this.userChartOpts,
						taskChartOpts: this.taskChartOpts,
						tradeChartOpts: this.tradeChartOpts
					})
				})
			} catch (error) {
				console.error('加载数据失败:', error)
				uni.showToast({
					title: '数据加载失败',
					icon: 'none'
				})
			} finally {
				this.loading = false
			}
		},
		//用户数据
		async loadUserData() {
			if (this.useRealData) {
				// 使用真实数据
				try {
					const result = await uniCloud.callFunction({
						name: 'getAnalyticsData',
						data: {
							dataType: 'user',
							month: this.month
						}
					})
					if (result.result.code === 200) {
						const data = result.result.data
						this.userStats = {
							total: data.total,
							monthlyNew: data.monthlyNew,
							active: data.active
						}
						// 保存真实的增长数据用于图表
						this.realUserGrowthData = data.growthData
					} else {
						throw new Error(result.result.message)
					}
				} catch (error) {
					console.error('获取用户数据失败:', error)
					uni.showToast({
						title: '获取用户数据失败，使用模拟数据',
						icon: 'none'
					})
					this.loadMockUserData()
				}
			} else {
				// 使用模拟数据
				this.loadMockUserData()
			}
		},
		
		// 加载模拟用户数据
		loadMockUserData() {
			this.userStats = { 
				total: 15847, 
				monthlyNew: 1850, 
				active: 9200 
			}
		},
		//任务数据
		async loadTaskData() {
			if (this.useRealData) {
				// 使用真实数据
				try {
					const result = await uniCloud.callFunction({
						name: 'getAnalyticsData',
						data: {
							dataType: 'task',
							month: this.month
						}
					})
					if (result.result.code === 200) {
						const data = result.result.data
						this.taskStats = {
							total: data.total,
							completed: data.completed,
							completionRate: data.completionRate
						}
						// 保存真实的任务量数据用于图表
						this.realTaskVolumeData = data.volumeData
						// 基于真实数据生成完成率数据
						this.realTaskCompletionData = data.volumeData.map(item => ({
							date: item.date,
							rate: item.published > 0 ? ((item.completed / item.published) * 100).toFixed(1) : 0
						}))
						// 生成模拟的任务分类数据（实际项目中应该从数据库获取）
						this.realTaskCategoryData = [
							{ category: '代购服务', count: Math.floor(data.total * 0.35) },
							{ category: '学习辅导', count: Math.floor(data.total * 0.25) },
							{ category: '技术服务', count: Math.floor(data.total * 0.20) },
							{ category: '生活服务', count: Math.floor(data.total * 0.15) },
							{ category: '其他', count: Math.floor(data.total * 0.05) }
						]
					} else {
						throw new Error(result.result.message)
					}
				} catch (error) {
					console.error('获取任务数据失败:', error)
					uni.showToast({
						title: '获取任务数据失败，使用模拟数据',
						icon: 'none'
					})
					this.loadMockTaskData()
				}
			} else {
				// 使用模拟数据
				this.loadMockTaskData()
			}
		},
		
		// 加载模拟任务数据
		loadMockTaskData() {
			this.taskStats = { 
				total: 2100, 
				completed: 1680, 
				completionRate: 80 
			}
		},
		//交易数据
		async loadTradeData() {
			if (this.useRealData) {
				// 使用真实数据
				try {
					const result = await uniCloud.callFunction({
						name: 'getAnalyticsData',
						data: {
							dataType: 'trade',
							month: this.month
						}
					})
					if (result.result.code === 200) {
						const data = result.result.data
						this.tradeStats = {
							totalAmount: data.totalAmount,
							totalCount: data.totalCount,
							avgAmount: data.avgAmount
						}
						// 保存真实的交易数据用于图表
						this.realTradeChartData = data.chartData
						// 基于真实数据生成消费习惯数据（按时间段统计）
						if (data.chartData && data.chartData.length > 0) {
							this.realTradeHabitData = [
								{ period: '0-6点', amount: Math.floor(data.totalAmount * 0.08), count: Math.floor(data.totalCount * 0.05) },
								{ period: '6-12点', amount: Math.floor(data.totalAmount * 0.25), count: Math.floor(data.totalCount * 0.22) },
								{ period: '12-18点', amount: Math.floor(data.totalAmount * 0.42), count: Math.floor(data.totalCount * 0.48) },
								{ period: '18-24点', amount: Math.floor(data.totalAmount * 0.25), count: Math.floor(data.totalCount * 0.25) }
							]
						}
					} else {
						throw new Error(result.result.message)
					}
				} catch (error) {
					console.error('获取交易数据失败:', error)
					uni.showToast({
						title: '获取交易数据失败，使用模拟数据',
						icon: 'none'
					})
					this.loadMockTradeData()
				}
			} else {
				// 使用模拟数据
				this.loadMockTradeData()
			}
		},
		
		// 加载模拟交易数据
		loadMockTradeData() {
			this.tradeStats = {
				totalAmount: '185,600.00',
				totalCount: 1247,
				avgAmount: '148.80'
			}
		},
		
		async loadRiskData() {
			if (this.useRealData) {
				// 使用真实风险数据
				try {
					console.log('正在加载真实风险数据...')
					
					// 直接调用风险分析云函数
					const result = await uniCloud.callFunction({
						name: 'riskAnalysis',
						data: {
							analysisType: 'overview',
							timeRange: 30
						}
					})
					
					console.log('风险分析云函数返回结果:', result)
					
					if (result.result && result.result.code === 200) {
						this.riskData = result.result.data
						console.log('真实风险数据加载成功:', this.riskData)
						uni.showToast({
							title: '真实风险数据加载成功',
							icon: 'success',
							duration: 1500
						})
					} else {
						throw new Error(result.result?.message || '风险分析云函数调用失败')
					}
				} catch (error) {
					console.error('风险分析云函数调用失败:', error)
					
					// 尝试回退到 getAnalyticsData 云函数
					try {
						console.log('尝试使用 getAnalyticsData 获取风险数据...')
						const fallbackResult = await uniCloud.callFunction({
							name: 'getAnalyticsData',
							data: {
								dataType: 'risk',
								month: this.month
							}
						})
						
						if (fallbackResult.result && fallbackResult.result.code === 200) {
							this.riskData = fallbackResult.result.data
							console.log('备用风险数据加载成功:', this.riskData)
							uni.showToast({
								title: '备用真实数据加载成功',
								icon: 'success',
								duration: 1500
							})
						} else {
							throw new Error('备用云函数也调用失败')
						}
					} catch (fallbackError) {
						console.error('备用风险数据获取也失败:', fallbackError)
						uni.showToast({
							title: '真实数据获取失败，使用模拟数据',
							icon: 'none',
							duration: 2000
						})
						this.loadMockRiskData()
					}
				}
			} else {
				// 使用模拟数据
				console.log('使用模拟风险数据')
				this.loadMockRiskData()
			}
			
			// 计算风险等级
			this.calculateRiskLevel()
		},
		
		// 加载模拟风险数据
		loadMockRiskData() {
			this.riskData = {
				highDefaultTasks: [
					{ type: '外卖代拿', rate: 15.2, total: 100, cancelled: 15, completed: 80 },
					{ type: '快递代拿', rate: 8.7, total: 120, cancelled: 10, completed: 105 },
					{ type: '出二手物', rate: 6.3, total: 80, cancelled: 5, completed: 70 },
					{ type: '求购', rate: 4.1, total: 90, cancelled: 4, completed: 85 }
				],
				violationUsers: [
					{ id: 1, nickname: '用户***123', violationCount: 5 },
					{ id: 2, nickname: '用户***456', violationCount: 4 },
					{ id: 3, nickname: '用户***789', violationCount: 3 },
					{ id: 4, nickname: '用户***012', violationCount: 2 }
				],
				abnormalTransactions: [
					{ id: 1, description: '【模拟】短时间大量低价发布', level: 'high', levelText: '高风险' },
					{ id: 2, description: '【模拟】异常退款申请', level: 'medium', levelText: '中风险' },
					{ id: 3, description: '【模拟】可疑账户关联', level: 'low', levelText: '低风险' },
					{ id: 4, description: '【模拟】重复任务发布', level: 'medium', levelText: '中风险' }
				],
				overallRisk: { text: '低风险', class: 'low' },
				summary: {
					taskTypes: 4,
					violationUsers: 4,
					anomalies: 4,
					totalRisks: 12
				}
			}
		},
		
			// 计算风险等级
		calculateRiskLevel() {
			// 如果真实数据中包含整体风险等级，直接使用
			if (this.riskData.overallRisk) {
				this.riskLevel = this.riskData.overallRisk
				return
			}
			
			// 否则根据异常交易数量计算
			const highRiskCount = this.riskData.abnormalTransactions.filter(t => t.level === 'high').length
			if (highRiskCount > 2) {
				this.riskLevel = { text: '高风险', class: 'high' }
			} else if (highRiskCount > 0) {
				this.riskLevel = { text: '中风险', class: 'medium' }
			} else {
				this.riskLevel = { text: '低风险', class: 'low' }
			}
		},
		
		
		updateOverviewMetrics() {
			this.overviewMetrics[0].value = this.userStats.total.toLocaleString()
			this.overviewMetrics[0].trend = 12.5
			
			this.overviewMetrics[1].value = this.taskStats.total.toLocaleString()
			this.overviewMetrics[1].trend = 8.3
			
			this.overviewMetrics[2].value = `¥${this.tradeStats.totalAmount}`
			this.overviewMetrics[2].trend = 15.7
			
			this.overviewMetrics[3].value = this.riskLevel.text
			this.overviewMetrics[3].trend = -2.1
		},
		
		// 设置所有图表
		setupAllCharts() {
			this.setupUserChart()
			this.setupTaskChart()
			this.setupTradeChart()
		},
		
		// 配置用户图表
		setupUserChart() {
			// qiun-data-charts格式的数据配置
			this.userChartOpts = {
				color: ['#667eea', '#91CB74', '#FAC858'],
				padding: [15, 15, 0, 15],
				enableScroll: false,
				legend: {},
				xAxis: {
					disableGrid: false
				},
				yAxis: {
					gridType: 'dash',
					dashLength: 2
				},
				extra: {
					line: {
						type: 'curve',
						width: 2,
						activeType: 'hollow'
					}
				}
			}
			
			// 根据当前选中的tab显示不同数据
			if (this.userActiveTab === 'growth') {
				// 用户增长数据
				if (this.useRealData && this.realUserGrowthData) {
					this.userChartData = {
						categories: this.realUserGrowthData.map(item => `09-${item.date}`),
						series: [{
							name: '用户数',
							data: this.realUserGrowthData.map(item => item.count)
						}]
					}
					} else {
					this.userChartData = {
						categories: ['09-15', '09-16', '09-17', '09-18', '09-19', '09-20', '09-21'],
						series: [{
							name: '用户数',
							data: [12000, 12800, 13200, 14100, 14800, 15200, 15847]
						}]
					}
				}
			} else if (this.userActiveTab === 'active') {
				// 用户活跃度数据
				this.userChartData = {
					categories: ['09-15', '09-16', '09-17', '09-18', '09-19', '09-20', '09-21'],
					series: [
						{
							name: '日活跃',
							data: [7200, 7680, 7920, 8460, 8880, 9120, 9200]
						},
						{
							name: '周活跃',
							data: [9600, 10240, 10560, 11280, 11840, 12160, 12267]
						}
					]
				}
			}
		},
		
		// 配置任务图表
		setupTaskChart() {
			// 根据当前选中的tab显示不同数据和图表类型
			if (this.taskActiveTab === 'volume') {
				// 任务发布量 - 柱状图
				this.taskChartOpts = {
					color: ['#f093fb', '#4facfe'],
					padding: [15, 15, 0, 15],
					enableScroll: false,
					legend: {},
					xAxis: {
						disableGrid: true
					},
					yAxis: {
						gridType: 'dash',
						dashLength: 2
					},
					extra: {
						column: {
							type: 'group',
							width: 30,
							activeBgColor: '#000000',
							activeBgOpacity: 0.08
						}
					}
				}
				
				if (this.useRealData && this.realTaskVolumeData) {
					this.taskChartData = {
						categories: this.realTaskVolumeData.map(item => `09-${item.date}`),
						series: [
							{
								name: '发布',
								data: this.realTaskVolumeData.map(item => item.published)
							},
							{
								name: '完成',
								data: this.realTaskVolumeData.map(item => item.completed)
							}
						]
					}
				} else {
					this.taskChartData = {
						categories: ['09-15', '09-16', '09-17', '09-18', '09-19', '09-20', '09-21'],
						series: [
							{
								name: '发布',
								data: [180, 220, 160, 240, 200, 280, 320]
							},
							{
								name: '完成',
								data: [145, 185, 120, 200, 165, 235, 275]
							}
						]
					}
				}
			} else if (this.taskActiveTab === 'completion') {
				// 任务完成率 - 折线图
				this.taskChartOpts = {
					color: ['#4facfe', '#91CB74'],
					padding: [15, 15, 0, 15],
					enableScroll: false,
					legend: {},
					xAxis: {
						disableGrid: false
					},
					yAxis: {
						gridType: 'dash',
						dashLength: 2
					},
					extra: {
						line: {
							type: 'curve',
							width: 2,
							activeType: 'hollow'
						}
					}
				}
				
				if (this.useRealData && this.realTaskCompletionData) {
					this.taskChartData = {
						categories: this.realTaskCompletionData.map(item => `09-${item.date}`),
						series: [{
							name: '完成率(%)',
							data: this.realTaskCompletionData.map(item => parseFloat(item.rate))
						}]
					}
				} else {
					this.taskChartData = {
						categories: ['09-15', '09-16', '09-17', '09-18', '09-19', '09-20', '09-21'],
						series: [{
							name: '完成率(%)',
							data: [80.6, 84.1, 75.0, 83.3, 82.5, 83.9, 85.9]
						}]
					}
				}
			} else if (this.taskActiveTab === 'category') {
				// 任务分类 - 饼图数据(用柱状图模拟)
				this.taskChartOpts = {
					color: ['#667eea', '#f093fb', '#4facfe', '#91CB74', '#FAC858'],
					padding: [15, 15, 0, 15],
					enableScroll: false,
					legend: {},
					xAxis: {
						disableGrid: true
					},
					yAxis: {
						gridType: 'dash',
						dashLength: 2
					},
					extra: {
						column: {
							type: 'group',
							width: 30,
							activeBgColor: '#000000',
							activeBgOpacity: 0.08
						}
					}
				}
				
				if (this.useRealData && this.realTaskCategoryData) {
					this.taskChartData = {
						categories: this.realTaskCategoryData.map(item => item.category),
						series: [{
							name: '任务数量',
							data: this.realTaskCategoryData.map(item => item.count)
						}]
					}
				} else {
					this.taskChartData = {
						categories: ['代购服务', '学习辅导', '技术服务', '生活服务', '其他'],
						series: [{
							name: '任务数量',
							data: [456, 234, 189, 156, 98]
						}]
					}
				}
			}
		},
		
		// 配置交易图表
		setupTradeChart() {
			// 根据当前选中的tab显示不同数据和图表类型
			if (this.tradeActiveTab === 'amount') {
				// 交易额 - 面积图
				this.tradeChartOpts = {
					color: ['#4facfe', '#91CB74'],
					padding: [15, 15, 0, 15],
					enableScroll: false,
					legend: {},
					xAxis: {
						disableGrid: false
					},
					yAxis: {
						gridType: 'dash',
						dashLength: 2
					},
					extra: {
						area: {
							type: 'curve',
							opacity: 0.2,
							addLine: true,
							width: 2,
							gradient: true,
							activeType: 'hollow'
						}
					}
				}
				
				if (this.useRealData && this.realTradeChartData && this.realTradeChartData.length > 0) {
					this.tradeChartData = {
						categories: this.realTradeChartData.map(item => `09-${item.date}`),
						series: [{
							name: '交易额',
							data: this.realTradeChartData.map(item => item.amount)
						}]
					}
				} else {
					this.tradeChartData = {
						categories: ['09-15', '09-16', '09-17', '09-18', '09-19', '09-20', '09-21'],
						series: [{
							name: '交易额',
							data: [15800, 22400, 18600, 28900, 25300, 32100, 36500]
						}]
					}
				}
			} else if (this.tradeActiveTab === 'volume') {
				// 交易量 - 折线图
				this.tradeChartOpts = {
					color: ['#667eea', '#f093fb'],
					padding: [15, 15, 0, 15],
					enableScroll: false,
					legend: {},
					xAxis: {
						disableGrid: false
					},
					yAxis: {
						gridType: 'dash',
						dashLength: 2
					},
					extra: {
						line: {
							type: 'curve',
							width: 2,
							activeType: 'hollow'
						}
					}
				}
				
				if (this.useRealData && this.realTradeChartData && this.realTradeChartData.length > 0) {
					this.tradeChartData = {
						categories: this.realTradeChartData.map(item => `09-${item.date}`),
						series: [{
							name: '交易笔数',
							data: this.realTradeChartData.map(item => item.count)
						}]
					}
				} else {
					this.tradeChartData = {
						categories: ['09-15', '09-16', '09-17', '09-18', '09-19', '09-20', '09-21'],
						series: [{
							name: '交易笔数',
							data: [106, 134, 112, 173, 148, 189, 207]
						}]
					}
				}
			} else if (this.tradeActiveTab === 'habit') {
				// 消费习惯 - 柱状图
				this.tradeChartOpts = {
					color: ['#FAC858', '#91CB74', '#4facfe', '#f093fb'],
					padding: [15, 15, 0, 15],
					enableScroll: false,
					legend: {},
					xAxis: {
						disableGrid: true
					},
					yAxis: {
						gridType: 'dash',
						dashLength: 2
					},
					extra: {
						column: {
							type: 'group',
							width: 30,
							activeBgColor: '#000000',
							activeBgOpacity: 0.08
						}
					}
				}
				
				if (this.useRealData && this.realTradeHabitData) {
					this.tradeChartData = {
						categories: this.realTradeHabitData.map(item => item.period),
						series: [
							{
								name: '交易额',
								data: this.realTradeHabitData.map(item => item.amount)
							},
							{
								name: '交易量',
								data: this.realTradeHabitData.map(item => item.count)
							}
						]
					}
				} else {
					this.tradeChartData = {
						categories: ['0-6点', '6-12点', '12-18点', '18-24点'],
						series: [
							{
								name: '交易额',
								data: [5200, 18600, 32400, 28900]
							},
							{
								name: '交易量',
								data: [18, 89, 156, 134]
							}
						]
					}
				}
			}
		},
		
	}
}
</script>

<style scoped>
/* 引入阿里图标字体 */
@import url('@/static/fonts/iconfont.css');

/* 主容器 */
.analytics-page {
	padding: 32rpx;
	background: #f8fafc;
	min-height: calc(100vh - 100rpx);
}

/* 顶部工具栏 */
.toolbar {
	display: flex;
	justify-content: space-between;
	align-items: flex-start;
	margin-bottom: 40rpx;
	padding: 32rpx;
	background: #fff;
	border-radius: 20rpx;
	box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.04);
}

.toolbar-left .page-header {
	display: flex;
	flex-direction: column;
	gap: 8rpx;
}

.page-title {
	font-size: 48rpx;
	font-weight: 700;
	color: #1a202c;
	line-height: 1.2;
}

.page-subtitle {
	font-size: 28rpx;
	color: #718096;
	line-height: 1.4;
}

.toolbar-right {
	display: flex;
	align-items: center;
	gap: 24rpx;
}

.date-picker {
	cursor: pointer;
}

.picker-btn {
	display: flex;
	align-items: center;
	gap: 12rpx;
	padding: 16rpx 24rpx;
	background: #f7fafc;
	border: 2rpx solid #e2e8f0;
	border-radius: 16rpx;
	transition: all 0.3s ease;
	min-width: 200rpx;
	justify-content: center;
}

.picker-btn:hover {
	background: #edf2f7;
	border-color: #cbd5e0;
}

.picker-btn .iconfont {
	font-size: 28rpx;
	color: #4a5568;
}

.picker-text {
	font-size: 28rpx;
	color: #2d3748;
	font-weight: 500;
}

.toggle-data-btn {
	display: flex;
	align-items: center;
	gap: 12rpx;
	padding: 16rpx 32rpx;
	background: #f7fafc;
	color: #4a5568;
	border: 2rpx solid #e2e8f0;
	border-radius: 16rpx;
	font-size: 28rpx;
	font-weight: 600;
	transition: all 0.3s ease;
	margin-right: 24rpx;
}

.toggle-data-btn.active {
	background: linear-gradient(135deg, #48bb78 0%, #38a169 100%);
	color: #fff;
	border-color: #38a169;
	box-shadow: 0 4rpx 15rpx rgba(72, 187, 120, 0.4);
}

.toggle-data-btn:hover {
	transform: translateY(-2rpx);
}

.toggle-data-btn .iconfont {
	font-size: 28rpx;
}

.refresh-btn {
	display: flex;
	align-items: center;
	gap: 12rpx;
	padding: 16rpx 32rpx;
	background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
	color: #fff;
	border: none;
	border-radius: 16rpx;
	font-size: 28rpx;
	font-weight: 600;
	transition: all 0.3s ease;
	box-shadow: 0 4rpx 15rpx rgba(102, 126, 234, 0.4);
}

.refresh-btn:hover {
	transform: translateY(-2rpx);
	box-shadow: 0 6rpx 20rpx rgba(102, 126, 234, 0.5);
}

.refresh-btn .iconfont {
	font-size: 28rpx;
}

/* 核心指标卡片 */
.overview-cards {
	display: grid;
	grid-template-columns: repeat(auto-fit, minmax(300rpx, 1fr));
	gap: 32rpx;
	margin-bottom: 40rpx;
}

.metric-card {
	display: flex;
	align-items: center;
	gap: 24rpx;
	padding: 32rpx;
	background: #fff;
	border-radius: 20rpx;
	box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.04);
	transition: all 0.3s ease;
	position: relative;
	overflow: hidden;
}

.metric-card::before {
	content: '';
	position: absolute;
	top: 0;
	left: 0;
	right: 0;
	height: 6rpx;
	background: var(--card-color, #667eea);
}

.metric-card:hover {
	transform: translateY(-4rpx);
	box-shadow: 0 8rpx 30rpx rgba(0, 0, 0, 0.08);
}

.metric-icon {
	width: 80rpx;
	height: 80rpx;
	border-radius: 20rpx;
	display: flex;
	align-items: center;
	justify-content: center;
	flex-shrink: 0;
}

.metric-icon .iconfont {
	font-size: 40rpx;
	color: #fff;
}

.metric-content {
	flex: 1;
	display: flex;
	flex-direction: column;
	gap: 8rpx;
}

.metric-value {
	font-size: 48rpx;
	font-weight: 700;
	color: #1a202c;
	line-height: 1.2;
}

.metric-label {
	font-size: 28rpx;
	color: #718096;
	font-weight: 500;
}

.metric-trend {
	display: flex;
	align-items: center;
	gap: 8rpx;
	font-size: 24rpx;
	font-weight: 600;
}

.metric-trend.positive {
	color: #38a169;
}

.metric-trend.negative {
	color: #e53e3e;
}

.trend-icon {
	font-size: 28rpx;
}

/* 数据分析网格 */
.analytics-grid {
	display: grid;
	grid-template-columns: repeat(auto-fit, minmax(600rpx, 1fr));
	gap: 32rpx;
	margin-bottom: 40rpx;
	align-items: start;
}

/* 图表面板 */
.chart-panel {
	background: #fff;
	border-radius: 20rpx;
	overflow: visible;
	box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.04);
	transition: all 0.3s ease;
	position: relative;
	z-index: 1;
	min-height: 680rpx;
}

.chart-panel:hover {
	box-shadow: 0 8rpx 30rpx rgba(0, 0, 0, 0.08);
}

.panel-header {
	display: flex;
	justify-content: space-between;
	align-items: center;
	padding: 32rpx;
	border-bottom: 2rpx solid #f7fafc;
}

.panel-title {
	display: flex;
	align-items: center;
	gap: 16rpx;
	font-size: 32rpx;
	font-weight: 600;
	color: #2d3748;
}

.panel-icon {
	font-size: 36rpx;
	color: #667eea;
}

.panel-tabs {
	display: flex;
	gap: 8rpx;
	background: #f7fafc;
	padding: 6rpx;
	border-radius: 12rpx;
}

.tab-item {
	padding: 12rpx 24rpx;
	font-size: 26rpx;
	font-weight: 500;
	color: #718096;
	border-radius: 8rpx;
	cursor: pointer;
	transition: all 0.3s ease;
}

.tab-item.active {
	background: #fff;
	color: #667eea;
	box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);
}

.chart-container {
	padding: 20rpx;
	height: 480rpx;
	width: 100%;
	position: relative;
	overflow: visible;
}

.chart-canvas {
	width: 100%;
	height: 100%;
	background: transparent;
	display: block;
	margin: 0 auto;
}

.chart-stats {
	display: flex;
	justify-content: space-around;
	padding: 24rpx 32rpx 32rpx;
	border-top: 2rpx solid #f7fafc;
}

.stat-item {
	text-align: center;
}

.stat-label {
	display: block;
	font-size: 24rpx;
	color: #718096;
	margin-bottom: 8rpx;
}

.stat-value {
	display: block;
	font-size: 32rpx;
	font-weight: 700;
	color: #2d3748;
}

/* 风险监控面板 */
.risk-panel {
	grid-column: 1 / -1;
	background: #fff;
	border-radius: 20rpx;
	overflow: hidden;
	box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.04);
	border: 2rpx solid #fed7d7;
}

.risk-panel .panel-header {
	background: linear-gradient(135deg, #feb2b2 0%, #fed7d7 100%);
}

.risk-icon {
	color: #e53e3e !important;
}

.risk-level {
	display: flex;
	align-items: center;
	gap: 12rpx;
	padding: 12rpx 20rpx;
	border-radius: 12rpx;
	font-size: 26rpx;
	font-weight: 600;
}

.risk-level.low {
	background: #c6f6d5;
	color: #276749;
}

.risk-level.medium {
	background: #fef5e7;
	color: #b7791f;
}

.risk-level.high {
	background: #fed7d7;
	color: #c53030;
}

.risk-dot {
	width: 12rpx;
	height: 12rpx;
	border-radius: 50%;
	background: currentColor;
}

.risk-metrics {
	display: grid;
	grid-template-columns: repeat(auto-fit, minmax(400rpx, 1fr));
	gap: 32rpx;
	padding: 32rpx;
}

.risk-metric-card {
	padding: 24rpx;
	background: #fafafa;
	border-radius: 16rpx;
	border: 2rpx solid #f0f0f0;
}

.risk-metric-header {
	display: flex;
	justify-content: space-between;
	align-items: center;
	margin-bottom: 20rpx;
}

.risk-metric-title {
	font-size: 28rpx;
	font-weight: 600;
	color: #2d3748;
}

.risk-metric-count {
	display: inline-flex;
	align-items: center;
	justify-content: center;
	min-width: 40rpx;
	height: 40rpx;
	padding: 0 12rpx;
	background: #e53e3e;
	color: #fff;
	font-size: 24rpx;
	font-weight: 700;
	border-radius: 20rpx;
}

.risk-list {
	display: flex;
	flex-direction: column;
	gap: 16rpx;
}

.risk-item {
	display: flex;
	justify-content: space-between;
	align-items: center;
	padding: 16rpx 20rpx;
	background: #fff;
	border-radius: 12rpx;
	box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.04);
}

.risk-item-name {
	font-size: 26rpx;
	color: #2d3748;
	font-weight: 500;
}

.risk-item-rate,
.risk-item-count {
	font-size: 24rpx;
	font-weight: 600;
	color: #e53e3e;
}

.risk-item-level {
	padding: 6rpx 12rpx;
	border-radius: 8rpx;
	font-size: 22rpx;
	font-weight: 600;
}

.risk-item-level.high {
	background: #fed7d7;
	color: #c53030;
}

.risk-item-level.medium {
	background: #fef5e7;
	color: #b7791f;
}

.risk-item-level.low {
	background: #c6f6d5;
	color: #276749;
}


/* 响应式设计 */
@media (max-width: 1200px) {
	.analytics-grid {
		grid-template-columns: 1fr;
	}
	
	.risk-metrics {
		grid-template-columns: 1fr;
	}
}

@media (max-width: 768px) {
	.analytics-page {
		padding: 24rpx;
	}
	
	.toolbar {
		flex-direction: column;
		gap: 24rpx;
		align-items: stretch;
	}
	
	.toolbar-right {
		justify-content: space-between;
	}
	
	.overview-cards {
		grid-template-columns: 1fr;
	}
	
	.report-actions {
		flex-direction: column;
	}
	
	.report-btn {
		justify-content: center;
	}
}

/* 动画效果 */
@keyframes fadeInUp {
	from {
		opacity: 0;
		transform: translateY(30rpx);
	}
	to {
		opacity: 1;
		transform: translateY(0);
	}
}

.metric-card,
.chart-panel,
.risk-panel,
.report-section {
	animation: fadeInUp 0.6s ease-out;
}

.metric-card:nth-child(1) { animation-delay: 0.1s; }
.metric-card:nth-child(2) { animation-delay: 0.2s; }
.metric-card:nth-child(3) { animation-delay: 0.3s; }
.metric-card:nth-child(4) { animation-delay: 0.4s; }

/* 加载状态 */
.loading {
	opacity: 0.7;
	pointer-events: none;
}

/* 图表容器优化 */
.chart-container {
	position: relative;
	background: linear-gradient(135deg, #f8fafc 0%, #ffffff 100%);
}

.chart-canvas {
	border-radius: 12rpx;
}
</style> 